const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const fs = require('fs/promises')
const path = require('path')
const dayjs = require('dayjs')

const app = new Koa()
const router = new Router()

// 处理跨域
app.use(async (ctx, next) => {
 // 允许的源（根据实际需求修改）
 const allowedOrigins = [
    'http://localhost:5173',
    'http://192.178.28.40:5173',
    'http://your-production-domain.com'
  ]
  
  const origin = ctx.headers.origin
  if (allowedOrigins.includes(origin)) {
    ctx.set('Access-Control-Allow-Origin', origin)
    ctx.set('Access-Control-Allow-Credentials', 'true') // 关键配置
  }

  // 处理预检请求
  if (ctx.method === 'OPTIONS') {
    ctx.set({
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '86400' // 24小时缓存
    })
    ctx.status = 204 // No Content
    return
  }

  await next()
})

app.use(bodyParser())

// 数据上报接口
router.post('/api/report', async (ctx) => {
  const logEntry = {
    ...ctx.request.body,
    ip: ctx.ip,
    userAgent: ctx.headers['user-agent']
  }

  // 按日期存储日志
  const logPath = path.join(
    __dirname,
    'logs',
    `${dayjs().format('YYYY-MM-DD')}.log`
  )

  await fs.appendFile(logPath, JSON.stringify(logEntry) + '\n')
  
  ctx.body = { status: 'ok' }
})

// 数据统计接口
router.get('/api/stat', async (ctx) => {
  const { date = dayjs().format('YYYY-MM-DD') } = ctx.query
  
  try {
    const logPath = path.join(__dirname, 'logs', `${date}.log`)
    const data = await fs.readFile(logPath, 'utf-8')
    
    const logs = data
      .split('\n')
      .filter(Boolean)
      .map(JSON.parse)

    // 统计PV
    const pv = logs.filter(log => log.type === 'pv').length

    // 统计UV
    const uv = new Set(logs.map(log => log.uuid)).size

    ctx.body = {
      date,
      pv,
      uv
    }
  } catch (err) {
    ctx.body = {
      date,
      pv: 0,
      uv: 0
    }
  }
})

app.use(router.routes())

app.listen(5102, () => {
  console.log('Server running on http://localhost:5102')
})